package com.cyzy.service;

import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class NotificationService {

    private final Map<Integer, SseEmitter> userIdToEmitter = new ConcurrentHashMap<>();
    //项目启动时，将所有用户id与sse连接对象保存起来，方便后续推送消息
    public SseEmitter subscribe(Integer userId) {
        SseEmitter emitter = new SseEmitter(0L);
        SseEmitter old = userIdToEmitter.put(userId, emitter);
        if (old != null) {
            try { old.complete(); } catch (Exception ignored) {}
        }
        emitter.onTimeout(() -> userIdToEmitter.remove(userId));
        emitter.onCompletion(() -> userIdToEmitter.remove(userId));
        return emitter;
    }
    //sse推送方法
    public void pushToUser(Integer userId, Object data) {
        SseEmitter emitter = userIdToEmitter.get(userId);
        if (emitter == null) {
            return;
        }
        try {
            emitter.send(SseEmitter.event().name("message").data(data));
        } catch (IOException e) {
            userIdToEmitter.remove(userId);
            try { emitter.complete(); } catch (Exception ignored) {}
        }
    }
}




